<?php

function village_add_page($id) {
    return drupal_get_form('village_edit_form',$id);
}

function village_edit_page($id) {
    return drupal_get_form('village_edit_form', $id);
}

function village_edit_form($form, &$form_state) {
    drupal_add_js(drupal_get_path('module', 'village') .'/village_add_sub_plant.js', 'file');
    $id = isset($form_state['build_info']['args'][0]) ? $form_state['build_info']['args'][0] : NULL;
    if (!empty($id)) {
        $record = nonghua_data_load('village', 'addr_id', $id);
        if (empty($record)) {
            drupal_set_message(t('村落不存在！'), 'status', FALSE);
            return $form;
        }
    }
    $form['submit_id'] = array(
        '#type' => 'hidden',
    );
// 判断用户角色
    if(!nonghua_user_access('village', 'view', $id, !empty($record) ? $record->author_uid:0, 0) ){
        drupal_set_message(t('您没有权限查看本条数据！'), 'status', FALSE);
        return $form;
    }
    if( !empty($_GET['addr_id'])){
        $form['#addr_id'] = $_GET['addr_id'];
    }
    $form['address_fuzzy'] = _insert_address_autocomplete($form, $form_state,isset($record) && !empty($record)?$record->addr_id:'');
    $form['address'] = _insert_address_selection_form($form, $form_state,'address', 5, true,  !empty($record) ? $record->addr_id:'','');

//    $form['distributor'] = get_all_distributors(!empty($record) ? $record->distributor_id : '');
   $form['distributor_name'] = _insert_distributor_select_info($form,$form_state,$record->distributor_id);
    $form['population'] = array(
        '#type' => 'textfield',
        '#title' => '人口数量',
        '#default_value' => !empty($record) ? $record->population : '',
        '#size' => 32,
        '#maxlength' => 6,
        '#required' => TRUE,
    );
    $form['income_average'] = array(
        '#type' => 'textfield',
        '#title' => '平均收入',
        '#default_value' => !empty($record) ? $record->income_average : '',
        '#required' => TRUE,
    );
    $form['farm_area'] = array(
        '#type' => 'textfield',
        '#title' => '耕地面积',
        '#default_value' => !empty($record) ? $record->farm_area : '',
        '#required' => TRUE,
    );
    $form['soil_condition'] = array(
        '#type' => 'textfield',
        '#title' => '土壤条件',
        '#default_value' => !empty($record) ? $record->soil_condition : '',
        '#required' => TRUE,
        '#maxlength' => 50
    );
    $form['comments'] = array(
        '#type' => 'textarea',
        '#title' => '其他',
        '#default_value' => !empty($record) ? $record->comments : '',
        '#maxlength' => 100,
        '#attributes'=>array('placeholder'=>'最多输入100字。')
    );
    insert_special_activities($form,$form_state,isset($record) && !empty($record)?$record:'');
    $form['plant']['#value'] =  !empty($record)?village_plant_list($record->addr_id):array();
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => arg(1) != 'add' ? '修改' : '添加',
        '#access' =>  nonghua_user_access('village', 'edit', $id, !empty($record) ? $record->author_uid:0, 0) ,
    );
    return $form;
}

function village_edit_form_validate(&$form, &$form_state) {
    insert_village_plant_sub_info($form,$form_state);
    if(!empty($form_state['values']['farm_area'])){
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if(!preg_match ($reg, $form_state['values']['farm_area']) || (strlen(explode('.',$form_state['values']['farm_area'])[0])>8)) {
            form_set_error('farm_area', "耕地面积格式错误");
        }
    }
    if(empty($form_state['values']['distributor_name'])){
        form_set_error('distributor_name', "请选择经销商");
    }
    if(!empty($form_state['values']['income_average'])){
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if(!preg_match ($reg, $form_state['values']['income_average']) || (strlen(explode('.',$form_state['values']['income_average'])[0])>8)) {
            form_set_error('income_average',  "平均收入格式错误");
        }
    }
    if(!empty($form_state['values']['population'])){
        $reg = '/^\d{1,10}$/';
        if(!preg_match ($reg, $form_state['values']['population'])) {
            form_set_error('population', "人口数量格式错误");
        }
    }

    $validate = true;
    if(!empty($form_state['values']['address_fuzzy'])){
        $addr_object = addr_load_by_full_name($form_state['values']['address_fuzzy']);
        if(empty($addr_object)){
            form_set_error('address_fuzzy', '请根据提示输入正确（完整）的地址信息');
            $validate = false;
        }elseif($addr_object->geo_level !== "5"){
            form_set_error('address_fuzzy', '请根据提示输入村落地址信息');
        }

    }else if(empty($form_state['values']['village'])){
        form_set_error('village', '必须填写 地址,输入地址或点选省市县乡镇村地址，两种方式任选其一');
        $validate = false;
    }



   if(!isset($form_state['build_info']['args'][0]) && $validate){
        $record = db_select('village', 'u')
            ->condition('u.addr_id', _get_address_id_from_autocomplete_select($form_state))
            ->fields('u')
            ->execute()->fetchAssoc();
        if (!empty($record)) {
            form_set_error('', "该村落信息已存在！");
        }
    }

    if(!empty($form_state['values']['distributor_name'])){
        $distributor_id = get_id_from_string_field('distributor','distributor_id','distributor_name',$form_state['values']['distributor_name'],false);
        if(empty($distributor_id)){
            form_set_error('distributor_name', "经销商信息不存在！");
        }
    }

}

function village_edit_form_submit($form, &$form_state) {
    global $user;
    $id = isset($form_state['build_info']['args'][0]) ? $form_state['build_info']['args'][0] : NULL;
    $address =  _get_address_id_from_autocomplete_select($form_state);
    $transaction = db_transaction();
    try{
        if (arg(1) == 'add') { //add new village
            $nid = db_insert('village') // Table name no longer needs {}
            ->fields(array(
                'addr_id' => $address,
                'distributor_id' => get_id_from_string_field('distributor','distributor_id','distributor_name',$form_state['values']['distributor_name'],false),
                'population' => $form_state['values']['population'],
                'income_average' => $form_state['values']['income_average'],
                'farm_area' => $form_state['values']['farm_area'],
                'soil_condition' => $form_state['values']['soil_condition'],
                'comments' => $form_state['values']['comments'],
                'special_activities_id'=>get_id_from_string_field('special_activities','special_activities_id','title',$form_state['values']['special_activities']),
                'author_uid' => $user->uid,
                'timestamp' => time(),))
                ->execute();
                $ids = explode(',',$form_state['values']['submit_id']);
                _update_village_plant($address,$ids,"village_plant","addr_id");
                drupal_set_message(t('添加成功！'), 'status', FALSE);
                drupal_goto('village/add');
        } else {
            $nid = db_update('village')// edit exsting store. todo: update only modified fields
            ->fields(array(
                'addr_id' => $address,
                'distributor_id' => get_id_from_string_field('distributor','distributor_id','distributor_name',$form_state['values']['distributor_name'],false),
                'population' => $form_state['values']['population'],
                'income_average' => $form_state['values']['income_average'],
                'farm_area' => $form_state['values']['farm_area'],
                'soil_condition' => $form_state['values']['soil_condition'],
                'comments' => $form_state['values']['comments'],
                'special_activities_id'=>get_id_from_string_field('special_activities','special_activities_id','title',$form_state['values']['special_activities']),
                'author_uid' => $user->uid,
                'timestamp' => time(),))
                ->condition('addr_id', $id, '=')
                ->execute();
            $ids = explode(',',$form_state['values']['submit_id']);
            _update_village_plant($address,$ids,"village_plant","addr_id");
            drupal_set_message(t('修改成功！'), 'status', FALSE);
        }
    }catch (Exception $e){
        $transaction->rollback();
        watchdog_exception('village add', $e);
        throw $e;
    }

}
